package com.haiyou.dc.thread.test1;

/**
 * 线程安全：保证数据的准确性
 * 方法1：锁方法
 * 方法2：锁块
 */
public class SynBlockTest03 {

    public static void main(String[] args) {
        SysBlockWeb12306 unsafeWeb12306 = new SysBlockWeb12306();
        new Thread(unsafeWeb12306, "AAAA").start();
        new Thread(unsafeWeb12306, "BBBB").start();
        new Thread(unsafeWeb12306, "CCCC").start();
    }

}

class SysBlockWeb12306 implements Runnable {

    private Integer ticketNum = 10;
    private Boolean flag = true;

    @Override
    public void run() {
        while (flag) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            buy3();
        }
    }

    /**
     * 线程安全，尽可能锁住合理的范围
     * double checking 双重检测
     */
    public void buy3() {
        //检测是否有没票
        if (ticketNum <= 0) {
            flag = false;
            return;
        }
        synchronized (this) {
            //检测是否最后一张票
            if (ticketNum <= 0) {
                flag = false;
                return;
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "---->" + ticketNum--);
        }

    }

    /**
     * 线程不安全，应该锁的是不变的对象，因为票数会减少的
     */
    public void buy2() {
        synchronized (ticketNum) {
            if (ticketNum <= 0) {
                flag = false;
                return;
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "---->" + ticketNum--);
        }

    }

    public void buy1() {
        synchronized (this) {
            if (ticketNum <= 0) {
                flag = false;
                return;
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "---->" + ticketNum--);
        }

    }

    public synchronized void buy() {
        if (ticketNum <= 0) {
            flag = false;
            return;
        }
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "---->" + ticketNum--);
    }
}
